import re

def load_program(file_path: str) -> str:
    """
    从文件中加载程序。
    """
    with open(file_path, "r", encoding="utf-8") as f:
        return f.read()

def save_program(program_code: str, file_path: str):
    """
    将程序保存到文件。
    """
    with open(file_path, "w", encoding="utf-8") as f:
        f.write(program_code)

def apply_diff(original_code: str, diff: str) -> str:
    """
    将 SEARCH/REPLACE 格式的 diff 应用于原始代码。
    """
    diff_match = re.search(r"<<<<<<<< SEARCH\n(.*?)\n========\n(.*?)\n>>>>>>>> REPLACE", diff, re.DOTALL)
    if not diff_match:
        raise ValueError("无效的 diff 格式")

    search_block = diff_match.group(1)
    replace_block = diff_match.group(2)

    if search_block not in original_code:
        raise ValueError("在原始代码中未找到搜索块")

    return original_code.replace(search_block, replace_block)